/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package utn.tsb.tej.comunications.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import utn.tsb.tej.comunications.Preferences;

/**
 *
 * @author Carlos S. Moreno <CarlosS.Moreno@gmail.com>
 */
public class ThreadWaitingPlayers extends Thread {

    boolean keepWaiting;
    ServerSocket portListener;

    public ThreadWaitingPlayers(String str)
    {
        super(str);
        keepWaiting = true;
        try
        {
            portListener = new ServerSocket(Preferences.getPort());
        }
        catch (IOException e)
        {
            keepWaiting = false;
            e.printStackTrace();
        }

    }

    public void run()
    {
        try {
            portListener.setSoTimeout(500);
            System.out.println("Listening on port " + Preferences.getPort() + ".");
        } catch (SocketException ex) {
            keepWaiting = false;
            System.out.println("[E]Port Listener not initialized!");
            ex.printStackTrace();
        }
        while (keepWaiting)
        {
            try {
                new Thread (new NewPlayerRequest(portListener.accept())).start();

            }catch (SocketTimeoutException ex)
            {}
            catch (IOException ex) {
                keepWaiting = false;
                ex.printStackTrace();
            }

        }
        try {
            portListener.close();
            System.out.println("Listening no more!");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void stopWaiting()
    {
        keepWaiting = false;
    }

}
